<script setup>
import { onMounted, provide, ref } from "vue";
import useListData from "@/hooks/list-data";
import dayjs from "dayjs";
import cloneDeep from "lodash/cloneDeep";
import { myGradeApi } from "@/services/income";
import Nodata from "@/pages/components/nodata.vue";
import useFormat from "@/hooks/format";

const { formatCommas } = useFormat();

// 可选的最大时间（时间戳毫秒）
const filterDateMax = ref(undefined);
// 可选的最小时间（时间戳毫秒）
const filterDateMin = ref(undefined);
// form values
const filterFormValues = ref({
  filterDate: undefined, // 搜索日期
});
const keyword=ref('')
// init data loading
const initDataLoading = ref(true);
// list data
const listData = useListData({
  loadData: (params) => {
    const paramsData = cloneDeep({
      ...params,
      keyword:keyword.value,
      date:
        (filterFormValues.value.filterDate &&
          dayjs(filterFormValues.value.filterDate).format(`YYYY-MM`)) ||
        undefined,
    });
    return myGradeApi(paramsData);
  },
});

// 跳转到详情
const toDetail = (item) => {
  uni.navigateTo({
    url: "/pages/income-detail/Index?id=" + item.id,
  });
};

// 改变日期
const handChangeDate = (item) => {
  filterFormValues.value.filterDate = item.detail.value;
  listData.value.pullDownRefresh();
};

const setValue=(e)=>{
  setTimeout(() => {
    keyword.value=e.detail.value
  }, 10); 
  
  
}


const searchBut=(e)=>{
  listData.value.pullDownRefresh();
  
  
}

// init
const initData = async () => {
  try {
    initDataLoading.value = true;
    filterDateMax.value = dayjs().format("YYYY-MM");
    filterDateMin.value = dayjs().subtract(2, "year").format("YYYY-MM");
    filterFormValues.value.filterDate = dayjs().startOf("month").valueOf();
    Promise.all([]);
    listData.value.initData();
    initDataLoading.value = false;
  } catch (error) {
    initDataLoading.value = false;
  }
};


onMounted(() => {
  initData();
});

// provide
provide("filterFormValues", filterFormValues);
provide("listData", listData);
</script>

<template>
  <view class="container">
    <template v-if="!initDataLoading">
      <view class="filter-container">
        <view class="filter-client-number-warp">
          <view class="client-item-warp">
            <text>总收入(元)</text>
            <text style="font-size: 20px;margin-left: 8rpx;">¥</text>
            <up-count-to
              :decimals="2"
              :endVal="listData?.apiDataResult?.total?.income_price"
              separator=","
              :duration="100"
              color="#000"
              fontSize="20"
              bold
            ></up-count-to>
          </view>
          <view class="client-number-line"> </view>
          <view class="client-item-warp">
            <text>销售总额(元) </text>
            <text style="font-size: 20px;margin-left: 8rpx;">¥</text>
            <up-count-to
              :decimals="2"
              :endVal="listData?.apiDataResult?.total?.grade_price"
              separator=","
              :duration="100"
              color="#000"
              fontSize="20"
              bold
            ></up-count-to>
          </view>
        </view>
      </view>

      <!-- scroll view -->
      <scroll-view
        class="scroll-view"
        scrollY
        refresherEnabled
        :refresherTriggered="listData.refresherTriggered"
        @scrolltolower="listData.loadMoreData"
        @refresherrefresh="listData.pullDownRefresh"
        refresherBackground="#f5f5f5"
      >
        <view class="filter-date-warp">
          <view class="filter-date-item">
            <view class="filter-date-text">
              <picker
                mode="date"
                :value="filterFormValues.filterDate"
                :start="filterDateMin"
                fields="month"
                :end="filterDateMax"
                @change="handChangeDate"
              >
                <view class="uni-input">
                  {{ dayjs(filterFormValues.filterDate).format(`YYYY年MM月`) }}
                </view>
              </picker>
              <uni-icons type="down" size="14"></uni-icons>
            </view>
          </view>
          <view class="filter-date-item-search">
            <view class="search-icon-k">
            <image
              src="../../static/search.png"
              mode="widthFix"
              class="search-icon"
            ></image>
          </view>
            <!-- <view class="search-input"></view> -->

            <input type='text' confirm-type="search" :value='keyword' 
						placeholder='客户/订单编号' placeholder-class='placeholder' @input="setValue"
						@confirm="searchBut"></input>
          </view>
        </view>

        <view class="content">
          <view v-for="(item, index) in listData.dataSource" :key="index">
            <view class="bg-detail-warp">
              <view class="date-warp">
                <text class="date-text">{{ item.day || "-" }}</text>
                <view class="date-value date-value-idnex">
                  <text>单日收入合计:</text>
                  <up-text mode="price" :text="item.total_price" class="price-day"></up-text>
                </view>
              </view>
              <view
                class="shop-warp"
                @click="toDetail(ele)"
                v-for="(ele, eleIndex) in item.item"
                :key="eleIndex"
              >
                <view class="shop-info-warp">
                  <view class="shop-icon-warp">
                    <image src="../../static//shop-icon.png" mode="widthFix" />
                    <up-text
                      :lines="1"
                      :text="ele.storeOrder.order_sn || '-'"
                    ></up-text>
                  </view>
                  <view class="shop-right-warp">
                    <text
                      :class="[
                        ele.status === 1 && 'already-tag',
                        ele.status === 0 && 'awit-tag',
                      ]"
                    >
                      {{ ele.status_text || "-" }}
                    </text>
                    <text class="price-text">
                      +{{
                        (ele.commission && formatCommas(ele.commission)) || "-"
                      }}
                    </text>
                  </view>
                </view>
                <view class="client-content-warp">
                  <view class="client-content-item">
                    <text class="client-content-label">
                      客&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;户 :
                    </text>
                    <text>
                      {{ ele.buyUser.nickname || "" }}-{{
                        ele.into_type_text || ""
                      }}
                    </text>
                  </view>
                  <view class="client-content-item">
                    <text class="client-content-label">订单金额 : </text>
                    <text>
                      {{
                        (ele.storeOrder.total_price &&
                          formatCommas(ele.storeOrder.total_price)) ||
                        "-"
                      }}
                    </text>
                  </view>
                  <view class="client-content-item">
                    <text class="client-content-label">订单时间 : </text>
                    <text>{{ ele.create_at || "-" }}</text>
                  </view>
                </view>
              </view>
            </view>
          </view>

          <Nodata
            v-if="
              listData.dataSource &&
              listData.dataSource.length === 0 &&
              listData.pagination.status === 'noMore'
            "
          ></Nodata>
          <uni-load-more
            :status="listData.pagination.status"
            class="load-more"
            :contentText="{
              contentdown: '上拉显示更多',
              contentrefresh: '正在加载...',
              contentnomore: '没有更多数据了',
            }"
          />
        </view>
      </scroll-view>
      <br />
    </template>
    <view v-else>
      <view class="init-data-loading">
        <up-loading-icon></up-loading-icon>
      </view>
    </view>
  </view>
</template>

<style lang="scss" scoped>
@import "./Index.scss";
</style>
